/*
 * Copyright (c) 2011, Asiainfo-Linkage. All rights reserved.
 * Asiainfo-Linkage PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package edu.w106.platform.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * MD5加密类.
 * <p>
 * <b>标题：</b>MD5.
 * </p>
 * 
 * <p>
 * <b>描述：</b>
 * </p>
 * 
 * <p>
 * <b>版权：</b>Copyright (c) 2011 亚信联创
 * </p>
 * 
 * <p>
 * <b>工程：</b>core
 * </p>
 * 
 * @author tangxiucai
 * 
 * @version 1.0.0
 * 
 * @since 2011-10-18 下午11:32:02
 */
public final class MD5 {
    /**
     * 日志记录对象.
     */
    private static Log log = LogFactory.getLog(MD5.class);

    /**
     * 消息摘要对象.
     */
    private static MessageDigest md = null;

    /**
     * 构造方法。
     * 
     */
    private MD5() {
    }

    static {
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ne) {
            log.debug("NoSuchAlgorithmException: md5", ne);
        }
    }

    /**
     * 加密.
     * 
     * @param str
     *            目标串
     * @return 加密后的串
     */
    public static String encrypt(String str) {
        md.update(str.getBytes());
        byte[] digestc = md.digest();
        return toHexString(digestc);
    }

    /**
     * 转成十六进制字符串.
     * 
     * @param b
     *            目标字节数组
     * @return 生成的字符串
     */
    private static String toHexString(byte[] b) {
        byte[] hex = "0123456789ABCDEF".getBytes();
        byte[] buff = new byte[2 * b.length];

        final int num1 = 4;
        final int num2 = 0xf;
        for (int i = 0; i < b.length; i++) {
            buff[2 * i] = hex[b[i] >> num1 & num2];
            buff[2 * i + 1] = hex[b[i] & num2];
        }
        return new String(buff);
    }

    public static void main(String[] args) {
        String str = "admin";
        String s = MD5.encrypt(str);
        System.out.println(s);
    }

}
